<template>
  <view class="order-container">
    <!-- 订单状态筛选栏 -->
    <view class="title-container">
      <view class="title" v-for="(item, index) in orderStatusMap" :key="item.key">
        <view 
          class="title-btn" 
          :class="{ 'selected': selectIndex === index }" 
          @click="handleSelect(index)"
        >
          {{ item.text }}
        </view>
      </view>
    </view>
	  
    <!-- 空状态提示 -->
    <view v-if="!orderListShow.length && !isLoading" class="empty-tip">
      <image src="/static/empty-order.png" class="empty-icon" alt="暂无订单"></image>
      <text>暂无订单记录</text>
    </view>
    
    <!-- 加载状态 -->
    <view v-if="isLoading" class="empty-tip">
      <view class="loading-spinner"></view>
      <text>加载订单中，请稍候...</text>
    </view>
    
    <!-- 订单列表 -->
    <view class="order-card" v-for="order in orderListShow" :key="order.order_id">
      <view class="order-header">
        <view class="order-status" :class="`status-${getState(order.order_status) }`">
          {{ order.order_status }}
        </view>
        <view class="order-info">
          <view class="order-id"><text>订单号：{{ order.order_id }}</text></view>
          <view class="order-time">下单时间：{{ formatMessageTime(order.order_time) }}</view>
        </view>
      </view>
      
      <!-- 商品列表滚动区 -->
      <scroll-view class="scroll" scroll-x="true">
        <view class="img-box" v-for="product in order.products" :key="product.id">
          <image 
            class="goodimg" 
            :src="(product.images && product.images.length > 0 && product.images[0].url) || '/static/no-image.png'"
            mode="aspectFill"
            alt="商品图片"
          ></image>
          <view class="product-detail">单价:￥{{ product.price }}</view>
          <view class="product-detail">数量:{{ product.quantity }}</view>
          <view class="product-detail">小计:￥{{ product.sub_total }}</view>
        </view>
      </scroll-view>
      
      <!-- 订单合计 -->
      <view class="total">
        <view class="total-a"><text>共{{ order.products.length }}件</text></view>
        <view class="total-b">
          <text>合计</text>
          <text style="font-size: 32rpx; font-weight: 500;">￥{{ order.total_amount }}</text>
        </view>
      </view>
      
      <!-- 操作按钮 -->
      <view class="btn-box">
        <view class="btn" @click="handleMoreAction(order)">更多操作</view>
        <view class="btn" @click="handleComment(order)" v-if="order.order_status_key === 'completed'">
          服务评价
        </view>
        <view class="btn" @click="handleContactSeller(order)">联系卖家</view>
        <view class="btn" @click="handleBuyAgain(order)">再来一单</view>
      </view>
    </view>
    
    <!-- 加载更多 -->
    <view 
      v-if="hasMore && !isLoading && orderList.length > 0" 
      class="load-more" 
      @click="loadMore"
    >
      加载更多
    </view>
	<uni-popup type="bottom" ref="popup">
		<productList :products='buyAgainList' ></productList>
		
		
	</uni-popup>
  </view>
</template>

<script>
import formatMessageTime from '../../utils/formatMessageTime.js';
import productList from '../../components/shop/productList.vue';
const app = getApp().globalData;
const db=uniCloud.databaseForJQL()
const order = uniCloud.importObject('order', {
  customUI: true
});

export default {

		components:{
		productList
	},
  data() {
    return {
      isLoading: false,
      orderList: [],
      selectIndex: 0,
      page: 1,
      pageSize: 10,
      hasMore: true,
	  buyAgainList:[],
      orderStatusMap: [
        { key: 'all', text: '全部' },
        { key: 'pending', text: '待支付' },
        { key: 'delivering', text: '配送中' },
        { key: 'completed', text: '已完成' }
      ]
    };
  },
  
  computed: {
    orderListShow() {
      const statusKey = this.orderStatusMap[this.selectIndex].key;
      
      // 筛选订单
      const filtered = statusKey === 'all' 
        ? this.orderList 
        :this.orderList.filter(item => item.order_status_key === statusKey);
      
      // 按时间排序（最新在前）
      return filtered.slice().sort((a, b) => {
        return new Date(b.order_time) - new Date(a.order_time);
      });
    },
    
    storeData() {
      return this.$store.state.msg;
    }
  },
  
  watch: {
    orderListShow(newVal) {
      console.log('筛选后的订单列表:', newVal);
    }
  },
  
  onShow() {
    this.getOrderList();
  },
  
  onReachBottom() {
    // 触底加载更多
    this.loadMore();
  },
  
  methods: {
    formatMessageTime,
    getState(value){
	const obj=this.orderStatusMap.find(item=>item.text===value)
	return obj.key||''
	        
	},
    // 切换订单状态
    handleSelect(index) {
      this.selectIndex = index;
    },
    
    // 获取订单列表
    async getOrderList(loadMore = false) {
      if (!loadMore) {
        this.page = 1;
        this.orderList = [];
        this.hasMore = true;
      }
      
      this.isLoading = true;
      try {
        const res = await order.getOrder(this.storeData.user.userId, {
          page: this.page,
          pageSize: this.pageSize
        });
        
        if (res.code === 0) {
          const newOrders = res.data || [];
        
          // 合并订单数据
          this.orderList = loadMore 
            ? [...this.orderList, ...newOrders] 
            : newOrders;
            
          // 判断是否还有更多数据
          this.hasMore = newOrders.length === this.pageSize;
          this.page++;
        } else {
          this.hasMore = false;
          uni.showToast({ title: res.msg || '获取订单失败', icon: 'none' });
        }
      } catch (err) {
        console.error('获取订单列表失败:', err);
        uni.showToast({ title: '加载订单失败', icon: 'none' });
      } finally {
        this.isLoading = false;
      }
    },
    
    // 加载更多
    loadMore() {
      if (!this.isLoading && this.hasMore) {
        this.getOrderList(true);
      }
    },
    
    // 订单操作 - 更多
    handleMoreAction(order) {
      console.log('更多操作', order);
      // 实现取消订单、查看物流等逻辑
      uni.showActionSheet({
        itemList: ['取消订单', '查看物流', '订单详情'],
        success: (res) => {
          switch(res.tapIndex) {
            case 0:
              this.cancelOrder(order.order_id);
              break;
            case 1:
              this.viewLogistics(order.order_id);
              break;
            case 2:
              this.viewOrderDetail(order.order_id);
              break;
          }
        }
      });
    },
    
    // 订单操作 - 评价
    handleComment(order) {
      console.log('服务评价', order);
      uni.navigateTo({
        url: `/pages/comment/Comment?orderId=${order.order_id}`
      });
    },
    
    // 订单操作 - 联系卖家
    handleContactSeller(order) {
      console.log('联系卖家', order);
      // 跳转到聊天页面
      uni.navigateTo({
        url: `/pages/chat/Chat?sellerId=${order.seller_id}`
      });
    },
    
    // 订单操作 - 再来一单
 async   handleBuyAgain(order) {
    const ids=  order.products.map(item=>item.id)
	const res=await db.collection('sendgood').where({
		_id:db.command.in(ids)
	}).get() 
	if(res.data.length>0){
		this.buyAgainList=res.data
		console.log(this.buyAgainList);
	this.$refs.popup.open()
	}
	
	    
	
    },
    
    // 取消订单
    async cancelOrder(orderId) {
      try {
        const res = await order.cancelOrder(orderId);
        if (res.code === 0) {
          uni.showToast({ title: '取消订单成功' });
          this.getOrderList(); // 重新加载订单
        } else {
          uni.showToast({ title: res.msg || '取消失败', icon: 'none' });
        }
      } catch (err) {
        console.error('取消订单失败:', err);
        uni.showToast({ title: '取消订单失败', icon: 'none' });
      }
    },
    
    // 查看物流
    viewLogistics(orderId) {
      uni.navigateTo({
        url: `/pages/logistics/Logistics?orderId=${orderId}`
      });
    },
    
    // 查看订单详情
    viewOrderDetail(orderId) {
      uni.navigateTo({
        url: `/pages/order/OrderDetail?orderId=${orderId}`
      });
    }
  }
};
</script>

<style scoped>
.order-container {
  padding: 20rpx ;
  background-color: #f5f5f5;
  min-height: 100vh;
}

/* 标题筛选栏 */
.title-container {
  display: flex;
  padding: 20rpx;
  background-color: #f8f8f8;
  gap: 30rpx;
  overflow-x: auto;
  margin-bottom: 20rpx;
  border-radius: 16rpx;
}

.title {
  min-width: 120rpx;
  height: 60rpx;
  line-height: 60rpx;
  text-align: center;
  background-color: #ffffff;
  border-radius: 30rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
  transition: all 0.2s;
  flex-shrink: 0;
}

.title-btn {
  font-size: 28rpx;
  color: #333;
  transition: all 0.2s;
}

.title-btn.selected {
  background-color: #55aa7f;
  color: white;
  font-weight: 500;
  font-size: 30rpx;
  border-radius: 30rpx;
}

/* 订单卡片 */
.order-card {
  background-color: white;
  border-radius: 30rpx;
  margin-bottom: 20rpx;
  padding: 20rpx 20rpx;
  box-shadow: 0 10rpx 30rpx rgba(0,0,0,0.05);
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  border-bottom: 1rpx solid #f0f0f0;
  padding: 0 20rpx 10rpx;
  margin-bottom: 10rpx;
}

.order-status {
  display: flex;
  justify-content: center;
  align-items: center;
  min-width: 160rpx;
  height: 60rpx;
  font-size: 32rpx;
  padding: 8rpx 24rpx;
  border-radius: 40rpx;
  font-weight: 500;
}

.order-info {
  flex: 1;
  margin-left: 20rpx;
}

.order-id {
  font-size: 28rpx;
  font-weight: 300;
  color: #333;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.order-time {
  font-size: 26rpx;
  color: #666;
  margin-top: 8rpx;
}

/* 商品滚动区 */
.scroll {
  white-space: nowrap;
  padding: 10rpx 10rpx;
  min-width: 750rpx;
}

.img-box {
  display: inline-block;
  padding: 10rpx 10rpx;
  margin-right: 10rpx;
  border-radius: 10rpx;
  background-color: #f9f9f9;
}

.goodimg {
  width: 150rpx;
  height: 150rpx;
  border-radius: 20rpx;
  margin-bottom: 10rpx;
}

.product-detail {
  font-size: 26rpx;
  color: #666;
  margin-top: 6rpx;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 合计区域 */
.total {
  display: flex;
  width: 100%;
  font-size: 26rpx;
  height: 60rpx;
  padding: 10rpx 30rpx;
  align-items: center;
  justify-content: flex-end;
  border-top: 1rpx dashed #f0f0f0;
  margin-top: 10rpx;
}

.total-a {
  margin-right: 20rpx;
  color: #666;
}

.total-b {
	  margin-right: 20rpx;
  color: #333;
}

/* 操作按钮 */
.btn-box {
  display: flex;
  justify-content: flex-end;
  gap: 15rpx;
  padding: 15rpx 0;
  flex-wrap: wrap;
}

.btn {
  display: flex;
  justify-content: center;
  align-items: center;
  min-width: 120rpx;
  height: 60rpx;
  border-radius: 20rpx;
  border: 2rpx solid #eee;
  font-size: 26rpx;
  color: #333;
  background-color: #f9f9f9;
  transition: all 0.2s;
}

.btn:active {
  background-color: #f0f0f0;
}

/* 状态样式 */
.status-pending {
  color: #FF5722;
  background-color: #FFF3E0;
  border: 1rpx solid #FFE0B2;
}

.status-delivering {
  color: white;
  background-color: #55aa7f;
  border: 1rpx solid #A5D6A7;
}

.status-completed {
  color: #4CAF50;
  background-color: #E8F5E9;
  border: 1rpx solid #C8E6C9;
}

/* 空状态和加载状态 */
.empty-tip {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-top: 300rpx;
  color: #cbcbcb;
  gap: 20rpx;
}

.empty-icon {
  width: 120rpx;
  height: 120rpx;
  opacity: 0.5;
}

.loading-spinner {
  width: 40rpx;
  height: 40rpx;
  border: 4rpx solid #eee;
  border-top-color: #55aa7f;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

/* 加载更多 */
.load-more {
  height: 80rpx;
  line-height: 80rpx;
  text-align: center;
  color: #55aa7f;
  font-size: 28rpx;
  margin: 20rpx 0;
}

.load-more:active {
  background-color: #f0f0f0;
  border-radius: 40rpx;
}
</style>
